package com.klikmee.sms.core.base;

import java.text.MessageFormat;

import org.apache.log4j.Logger;

import com.klikmee.sms.core.base.communicator.DeliveryReport;
import com.klikmee.sms.core.commons.filters.ProcessItemFilter;
import com.klikmee.sms.core.commons.queues.QueueItem;
import com.klikmee.sms.core.commons.queues.QueueItemProcessor;

/**
 * Item processor for delivery report queue. Depends on a chain of item filters
 * to do the actual item processing.
 * 
 * @author makcro
 * 
 */
public class DeliveryReportQueueItemProcessorImpl implements QueueItemProcessor<DeliveryReport> {

	// logger instance
	private Logger								logger	= Logger.getLogger( DeliveryReportQueueItemProcessorImpl.class );

	/**
	 * Chain of item filters which do the actual processing.
	 */
	private ProcessItemFilter<DeliveryReport>[]	filterChain;

	/**
	 * Iterates through filter chain and offers item to each filter until some
	 * of them accepts it.
	 * 
	 * @param item
	 *            an item that is to be processed
	 * 
	 * @return true if any of the filters accepted item, false otherwise
	 */
	@Override
	public boolean process(QueueItem<DeliveryReport> item) {
		// presume that item is not accepted
		boolean accpeted = false;
		DeliveryReport deliveryReport = item.getPayload();

		for (ProcessItemFilter<DeliveryReport> filter : this.filterChain) {
			// offer item to the filter
			accpeted = filter.process( deliveryReport );
			// if item is accepted, break the loop
			if (accpeted) {
				logger.debug( MessageFormat.format( "Item {0} accepted by {1} filter", item, filter ) );
				break;
			}
			else {
				logger.debug( MessageFormat.format( "Item {0} rejected by {1} filter", item, filter ) );
			}
		}

		return accpeted;
	}

	public void setFilterChain(ProcessItemFilter<DeliveryReport>[] filterChain) {
		this.filterChain = filterChain;
	}

}
